<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车辆ID" prop="bicycleId">
        <el-input v-model="queryParams.bicycleId" placeholder="请输入车辆ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工单号" prop="orderId">
        <el-input v-model="queryParams.orderId" placeholder="请输入工单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="客户型号" prop="customerModel">
        <el-select v-model="queryParams.customerModel" placeholder="请选择审核状态" clearable>
          <el-option v-for="dict in dict.type.customer_model" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="颜色" prop="colour">
        <el-select v-model="queryParams.colour" filterable placeholder="请选择颜色" clearable>
          <el-option v-for="dict in dict.type.colour" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="销售订单号" prop="clientOrderNumber" label-width="85px">
        <el-input v-model="queryParams.clientOrderNumber" placeholder="请输入销售订单号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['orderwarehousing:orderwarehousing:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['orderwarehousing:orderwarehousing:edit']">修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['orderwarehousing:orderwarehousing:remove']">删除</el-button>
      </el-col> -->

      <el-col :span="1.5">
        <el-button type="audit" plain size="mini" :disabled="multiple" @click="handleAudit"
          v-hasPermi="['msgerror']">审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="audit" plain size="mini" :disabled="multiple" @click="UnhandleAudit"
          v-hasPermi="['orderwarehousing:orderwarehousing:unaudit']">反审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="audit" plain size="mini" :disabled="multiple" v-hasPermi="['packageWeighing:package:print']"
          @click="dialogVisibleprint = true">打印</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['orderwarehousing:orderwarehousing:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderwarehousingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车辆ID" align="center" prop="bicycleId" />
      <el-table-column v-for="(item, index) in fittings" :key="index" :label="item.fittingName" align="center"
        :prop="item.fittingFabienName" v-if="item.delFlag" />
      <el-table-column label="工单号" align="center" prop="orderId" />
      <el-table-column label="入库日期" align="center" prop="warehousingDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.warehousingDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="毛重" align="center" prop="grossWeight" />
      <el-table-column label="净重" align="center" prop="net" />
      <el-table-column label="客户订单号" align="center" prop="clientOrderNumber" />
      <el-table-column label="产品编号" align="center" prop="productId" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="规格型号" align="center" prop="specifications">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.specification_and_model" :value="scope.row.specifications" />
        </template>
      </el-table-column>
      <el-table-column label="客户型号" align="center" prop="customerModel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_model" :value="scope.row.customerModel" />
        </template>
      </el-table-column>
      <el-table-column label="外箱尺寸" align="center" prop="cartonSize">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.carton_size" :value="scope.row.cartonSize" />
        </template>
      </el-table-column>
      <el-table-column label="颜色" align="center" prop="color">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.colour" :value="scope.row.color" />
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="clientName" />
      <el-table-column label="单据编号" align="center" prop="documentsId" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="入库仓库" align="center" prop="warehouseId" />
      <el-table-column label="审核状态" align="center" prop="audit">
        <template #default="{ row }">
          <el-tag v-if="row.audit == 0" type="danger">未审核</el-tag>
          <el-tag v-if="row.audit == 2" type="success">已审核</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['orderwarehousing:orderwarehousing:edit']">修改</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['orderwarehousing:orderwarehousing:remove']">删除</el-button> -->
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="100" align="center">
        <template slot="header">
          <i class="el-icon-setting" style="font-size: 22px; cursor: pointer" @click="showColumnOption"></i>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <transition name="fade">
      <div class="columnOption" v-show="isShowColumn">
        <div class="content">
          <div class="head">选择显示字段</div>
          <div class="body">
            <el-checkbox v-for="(item, index) in fittings" :key="index" v-model="item.delFlag">{{ item.fittingName
            }}</el-checkbox>
          </div>
          <div class="footer">
            <el-button size="small" type="primary" plain @click="saveColumn">保存列配置</el-button>
          </div>
        </div>
      </div>
    </transition>
    <!-- 添加或修改其他入库单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车辆ID" prop="bicycleId">
          <el-input v-model="form.bicycleId" placeholder="请输入车辆ID" ref="bicycleId"
            @keyup.enter.native="nextGetFocusa('controllerId')" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="控制器号" prop="controllerId">
          <el-input v-model="form.controllerId" placeholder="请输入控制器号" ref="controllerId"
            @keyup.enter.native="nextGetFocusa(1)" />
        </el-form-item>
        <el-row>
          <div v-for="(item, index) in fittings" :key="index">
            <el-col :span="12">
              <el-form-item :label="item.fittingName" :prop="item.fittingFabienName">
                <el-input v-model="form.map[item.fittingFabienName]" :ref="item.fittingFabienName"
                  @keyup.enter.native="nextGetFocus(index, item.fittingFabienName)"></el-input>
              </el-form-item>
            </el-col>
          </div>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="工单号" prop="orderId">
              <el-input v-model="form.orderId" placeholder="请输入工单号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库日期" prop="warehousingDate">
              <el-date-picker clearable v-model="form.warehousingDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择入库日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户订单号" prop="clientOrderNumber">
              <el-input v-model="form.clientOrderNumber" placeholder="请输入客户订单号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="毛重" prop="grossWeight">
              <el-input v-model="form.grossWeight" placeholder="请输入毛重" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="净重" prop="net">
              <el-input v-model="form.net" placeholder="请输入净重" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据编号" prop="documentsId">
              <el-input v-model="form.documentsId" placeholder="请输入单据编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品编号" prop="productId">
              <el-input v-model="form.productId" placeholder="请输入产品编号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">

            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="form.clientName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <CustomSearch ref="WareHouseSearch2" label="默认仓库" prop="warehouseId" labelWidth="110px"
            :tableKeys="wareHouseTableKeys2" formTitle="选择仓库" primaryKey="warehouseId" showField="warehouseName"
            @getSearchList="getWareHouseSearchList2" @updateQueryParams="updateQueryParamsForWareHouse2"
            @selectDialogItem="selectDialogItemForWareHouse2"></CustomSearch>
          <el-col :span="8">
            <el-form-item label="入库仓库" prop="warehouseI">
              <el-input v-model="form.warehouseId" placeholder="请输入入库仓库" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 打印车辆显示 -->
    <el-dialog title="提示" :visible.sync="dialogVisibleprint" width="30%" :before-close="handleClose">
      <el-button type="audit" plain size="mini" v-print="print" @click="printOut">打印（出口）</el-button>
      <el-button type="audit" plain size="mini" v-print="print" @click="printIn">打印（内销）</el-button>
      <span slot="footer" class="dialog-footer">
        <el-button @click="printClose">取 消</el-button>
        <el-button type="primary" @click="printClose">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 打印车辆ID页面 -->
    <div class="qrCode-container" v-if="printun">
      <div id="printQrCode">
        <div v-for="(item, index) in this.printQrCode" :key="index" class="qrCode-content">
          <vue-qr ref="qrCode" :text="text(item).toString()"> </vue-qr>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { listOrderwarehousing, getOrderwarehousing, delOrderwarehousing, addOrderwarehousing, updateOrderwarehousing, updateUnAudit, updateAudit } from "@/api/storage/orderwarehousing/orderwarehousing";
import { selectFittings, selectFitting } from "@/api/storage/controller/bicycle";
import CustomSearch from "@/views/commons/CustomSearch.vue";
import { wareHouseSelect2 } from '@/mixins/wareHouse/wareHouseSelectForForm.js'
import print from 'vue-print-nb'
import VueQr from 'vue-qr'
export default {
  name: "Orderwarehousing",
  components: { CustomSearch, VueQr },
  mixins: [wareHouseSelect2],
  directives: {
    print
  },
  dicts: ['colour', 'product_line', 'close', 'audit', 'customer_model', 'carton_size', 'specification_and_model'],
  computed: {
    text() {
      return function (val) {
        const a = {
          "客户订单号": val.clientOrderNumber, "产品品号": val.productId, "产品名称": val.productName, "车辆ID": val.bicycleId,
          "控制器号": val.controllerId
        }
        this.fittings.map(res => {
          this.$set(a, res.fittingName, val.map[res.fittingFabienName])
        })
        const b = {
          "clientOrderNumber": val.clientOrderNumber, "productId": val.productId, "productName": val.productName, "bicycleId": val.bicycleId,
          "controllerId": val.controllerId,
        }
        this.fittings.map(res => {
          this.$set(b, res.fittingFabienName, val.map[res.fittingFabienName])
        })
        let c = ""
        if (this.export == true) {
          c = a
        } else {
          c = b
        }
        return JSON.stringify(c);
      }
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      //打印车辆内销、出库判断
      export: true,
      //判断打印车辆页面
      dialogVisibleprint: false,
      //筛选显示
      isShowColumn: false,
      fittings: [],
      //判断打印界面
      printun: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      disabled: false,
      // 非多个禁用
      multiple: true,
      classOption: "",
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 其他入库单表格数据
      orderwarehousingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //打印二维码页面选择
      printQrCode: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bicycleId: null,
        orderId: null,
      },
      // 表单参数
      form: {
        map: {}
      },
      print: {
        id: 'printQrCode',
        popTitle: '配置页眉标题', // 打印配置页上方的标题
        // 查看是否添加需求对打印进行优化
        // preview: false, // 是否启动预览模式，默认是false
        // previewTitle: '预览的标题', // 打印预览的标题
        // previewPrintBtnLabel: '预览结束，开始打印', // 打印预览的标题下方的按钮文本，点击可进入打印
        // zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
        // openCallback() {
        //   this.daying=true
        // }, // 调用打印时的callback
        // closeCallback() { console.log('关闭了打印工具！') }, // 关闭打印的callback(无法区分确认or取消)
      },
      // 表单校验
      rules: {
        bicycleId: [
          { required: true, message: "车辆ID不能为空", trigger: "blur" }
        ],
        controllerId: [
          { required: true, message: "控制器号不能为空", trigger: "blur" }
        ],
        warehousingDate: [
          { required: true, message: "入库日期不能为空", trigger: "blur" }
        ],
        grossWeight: [
          { required: true, message: "毛重不能为空", trigger: "blur" }
        ],
        net: [
          { required: true, message: "净重不能为空", trigger: "blur" }
        ],
        clientOrderNumber: [
          { required: true, message: "客户订单号不能为空", trigger: "blur" }
        ],
        productId: [
          { required: true, message: "产品编号不能为空", trigger: "blur" }
        ],
        clientName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        documentsId: [
          { required: true, message: "单据编号不能为空", trigger: "blur" }
        ],
        color: [
          { required: true, message: "颜色不能为空", trigger: "change" }
        ],
        warehouseId: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],
      }
    };
  },

  created() {
    this.getList();
    selectFittings().then(res => {
      this.fittings = res.data
      this.fittings.forEach(item => {
        if (item.delFlag == 0) {
          item.delFlag = true
        } else {
          item.delFlag = false
        }
      })
    })
    this.getDicts("accessory_type").then(res => {
      this.classOption = res.data
    })
  },
  methods: {
    showColumnOption() {
      this.isShowColumn = true;
    },
    saveColumn() {
      this.isShowColumn = false;
    },
    printClose() {
      this.dialogVisibleprint = false
      this.printun = false
    },
    printOut() {
      this.export = false
      this.printun = true
    },
    printIn() {
      this.export = true
      this.printun = true
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.printun = false
          done();
        })
        .catch(_ => { });
    },
    /** 查询其他入库单列表 */
    getList() {
      this.loading = true;
      listOrderwarehousing(this.queryParams).then(response => {
        this.orderwarehousingList = response.rows;
        this.orderwarehousingList.forEach(item => {
          this.fittings.forEach(it => {
            const fittingKeyName = it.fittingFabienName;
            if (item.map && item.map[fittingKeyName] && item.map[fittingKeyName] !== "") {
              item[fittingKeyName] = item.map[fittingKeyName]
            }
          })
        })
        this.total = response.total;
        this.loading = false;
      });

    },
    //下一个输入框获取焦点
    nextGetFocusa(nextRef) {
      if (nextRef === 1) {
        this.$refs[this.fittings[0].fittingFabienName][0].focus()
        let data = {};
        this.classOption.map(item => {
          if (item.dictValue == "controllerId") {
            data = {
              accessoryType: item.dictValue,
              data: this.form.controllerId
            }
          }
        })
        selectFitting(data).then(response => {
          if (response.code == 200) {
            this.speak("扫描成功");
          } else {
            this.speak("扫描失败");
          }
        }
        )
      } else {
        this.$refs[nextRef].focus()

      }
    },
    nextGetFocus(nextRef, thisRef) {
      if (nextRef != this.fittings.length - 1) {
        this.$refs[this.fittings[nextRef + 1].fittingFabienName][0].focus()
        let data = {};
        this.classOption.map(item => {
          if (item.dictValue == thisRef) {
            data = {
              accessoryType: item.dictValue,
              data: this.form.map[thisRef]
            }
          }
        })
        selectFitting(data).then(response => {
          if (response.code == 200) {
            this.speak("扫描成功");
          } else {
            this.speak("扫描失败");
          }
        }
        )
      }

    },
    //语音提示
    speak(text) {
      const msg = new SpeechSynthesisUtterance(text);
      window.speechSynthesis.speak(msg);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        bicycleId: null,
        controllerId: null,
        orderId: null,
        warehousingDate: null,
        grossWeight: null,
        net: null,
        map: {
          frameId: null
        },
        clientOrderNumber: null,
        productId: null,
        clientName: null,
        documentsId: null,
        remark: null,
        audit: null,
        color: null,
        warehouseId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.printQrCode = selection
      this.ids = selection.map(item => item.bicycleId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.disabled = false
      this.open = true;
      this.title = "添加其他入库单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.disabled = true
      const bicycleId = row.bicycleId || this.ids
      getOrderwarehousing(bicycleId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改其他入库单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let accessoryDataVos = []
      this.fittings.map(item => {
        let AccessoryDataVo = {
          fittingId: item.fittingId,
          accessoryType: item.fittingFabienName,
          data: this.form.map[item.fittingFabienName]
        }
        accessoryDataVos.push(AccessoryDataVo)
      })
      let AccessoryDataVo = {
        accessoryType: this.classOption[0].dictValue,
        data: this.form.controllerId
      }
      accessoryDataVos.push(AccessoryDataVo)
      this.$set(this.form, "accessoryDataVos", accessoryDataVos)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.disabled) {
            console.log(this.form);
            updateOrderwarehousing(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });

          } else {
            console.log(this.form);
            addOrderwarehousing(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 审核操作 */
    handleAudit(row) {
      const bicycleIds = row.ticketsId || this.ids;
      updateAudit(bicycleIds);
      this.getList();
      this.$modal.msgSuccess("审核成功");

    },
    UnhandleAudit(row) {
      const bicycleIds = row.ticketsId || this.ids;
      updateUnAudit(bicycleIds);
      this.getList();
      this.$modal.msgSuccess("反审核成功");

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const bicycleIds = row.bicycleId || this.ids;
      this.$modal.confirm('是否确认删除其他入库单编号为"' + bicycleIds + '"的数据项？').then(function () {
        return delOrderwarehousing(bicycleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('orderwarehousing/orderwarehousing/export', {
        ...this.queryParams
      }, `orderwarehousing_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.columnOption {
  position: fixed;
  z-index: 20;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: row-reverse;
}

.columnOption .content {
  width: 100px;
  height: 100%;
  background-color: rgb(203, 223, 198);
}

.columnOption .content .head {
  width: 100%;
  height: 44px;
  border-bottom: 1px solid #000;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
}

.columnOption .content .body {
  width: 100%;
  height: calc(100% - 88px);
  box-sizing: border-box;
  padding-top: 10px;
  overflow-y: auto;
}

.columnOption .content .body .items {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.columnOption .content .body .items .el-checkbox {
  width: 100%;
  height: 28px;
  line-height: 28px;
  margin-bottom: 14px;
  display: inline-block;
  font-family: PingFang SC;
  font-style: normal;
  font-weight: normal;
  font-size: 14px;
  color: #000;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  box-sizing: border-box;
  padding-left: 14px;
}

.columnOption .content .body .items .el-checkbox:hover {
  background-color: #f5f7fa;
}

.columnOption .content .footer {
  width: 100%;
  height: 44px;
  border-top: 1px solid #000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
